package com.yx.shiroboot.controller;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/to")
public class UserController {

    /*@GetMapping("/userLogin")
    @ResponseBody
    public String userLogin(String name,String pwd){
        //1、获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //2、封装请求数据到token
        AuthenticationToken token = new UsernamePasswordToken(name,pwd);
        //3、调用login方法进行登录认证
        try {
            subject.login(token);
            return "登陆成功";
        } catch (AuthenticationException e) {
            System.out.println("登陆失败");
//            throw new RuntimeException(e);
            e.printStackTrace();
            return "登陆失败";
        }


    }
*/
    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/userLogin")
    public String userLogin(String name, String pwd, HttpSession session){
//1、获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //2、封装请求数据到token
        AuthenticationToken token = new UsernamePasswordToken(name,pwd);
        //3、调用login方法进行登录认证
        try {
            subject.login(token);
//            return "登陆成功";
            session.setAttribute("user",token.getPrincipal().toString());
            return "home";
        } catch (AuthenticationException e) {
            System.out.println("登陆失败");
//            throw new RuntimeException(e);
            e.printStackTrace();
            return "登陆失败";
        }
    }

}
